﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Odyssey.Http.Implementations
{
    internal partial class HttpRequester : IHttpRequester
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IHttpSerializer _httpSerializer;
        private readonly IHttpConfiguration _httpConfiguration;
        private readonly ILogger _logger;

        public HttpRequester(IHttpClientFactory httpClientFactory, IHttpSerializer httpSerializer, IHttpConfiguration httpConfiguration, ILogger<HttpRequester> logger)
        {
            _httpClientFactory = httpClientFactory;
            _httpSerializer = httpSerializer;
            _httpConfiguration = httpConfiguration;
            _logger = logger;
        }

        public virtual async Task<T> GetAsync<T>(string uri, string clientName = "", IDictionary<string, string> requestHeaders = null, IHttpSerializer httpSerializer = null)
        {
            return await GetAsync<T>(new Uri(uri), clientName, requestHeaders, httpSerializer);
        }

        public virtual async Task<T> GetAsync<T>(Uri uri, string clientName = "", IDictionary<string, string> requestHeaders = null, IHttpSerializer httpSerializer = null)
        {
            httpSerializer = httpSerializer ?? _httpSerializer;
            var responseJsonString = await GetAsync(uri, clientName, requestHeaders);
            return httpSerializer.Deserialize<T>(responseJsonString);
        }

        public virtual async Task<string> GetAsync(string uri, string clientName = "", IDictionary<string, string> requestHeaders = null)
        {
            return await GetAsync(new Uri(uri), clientName, requestHeaders);
        }

        public virtual async Task<string> GetAsync(Uri uri, string clientName = "", IDictionary<string, string> requestHeaders = null)
        {
            if (string.IsNullOrWhiteSpace(clientName))
            {
                clientName = _httpConfiguration.DefaultClientName;
            }
            var httpResponseMessage = await SendAsync(uri, string.Empty, HttpMethod.Get, clientName, requestHeaders: requestHeaders);
            var responseJsonString = await httpResponseMessage.Content.ReadAsStringAsync();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation($"get uri=[{uri.ToString()}] response data=[{responseJsonString}]");
            }
            return responseJsonString;
        }
    }
}
